<template>
<!--  <q-scroll-area class="home-scroll" :thumb-style="CommonConfig.thumbStyle">-->
    <div class="prod" v-if="isProd">
      <img src="statics/img/home-content.png" />
      <h1 class="txt">欢迎使用语祯物联数字化精益平台</h1>
    </div>
    <div v-else class="home home-scroll scrollbar">
      <div class="left">
        <div class="line1 flex">
          <div class="flex-item">
            <div class="top-head small-title">
              当前班制：{{shifts.name}}
              <span v-if="shifts.name.length>0" class="small-title">
              ({{shifts.startTime}}—{{shifts.endTime}})
            </span>
              <span>{{workFlagName}}</span>
<!--              <q-btn outline color="primary" style="width: 110px" label="跳转新闻页" @click="$router.push( '/main/home/new')" />-->
            </div>
            <box title="当日实时状态分布" class="content" @big="showPieDialog(realTimeStatus, realTimeTotal, '实时状态分布', 'percent')">
              <template v-slot:content>
                <pie :info="realTimeStatus" :total="realTimeTotal"></pie>
              </template>
            </box>
          </div>
          <div class="flex-item">
            <div class="top-head text-center">
              {{selTree.factory.label==='default'?userInfo.company_name:selTree.factory.label}}—{{selTree.plant.label}}
            </div>
            <div class="content">
              <box title="当班状态统计" class="content" @big="showPieDialog(curStatus, curTotal, '当班状态统计', 'time')">
                <template v-slot:content>
                  <CurStatus :info="curStatus" :total="curTotal" type="time"></CurStatus>
                </template>
              </box>
            </div>
          </div>
        </div>
        <div class="line2">
          <box title="当班停机原因" @big="showBarDialog">
            <template v-slot:content>
              <div class="barChart" ref="barChart"></div>
            </template>
          </box>
        </div>
        <div class="line3">
          <box title="当班不良统计" @big="showLineDialog">
            <template v-slot:content>
              <div class="lineChart" ref="lineChart"></div>
            </template>
          </box>
        </div>
      </div>
      <div class="right">
        <div class="top-head text-right">
          <q-toggle v-model="showScale"
                    label="启用缩放"
                    left-label
                    @input="changeScale"
                    size="16px"

          />
          <q-btn @click="showSelPlantDialog" class="more-btn" round flat dense size="sm" color="primary" icon="iconfont icontubiao-74" />
        </div>

        <div class="box">
          <div class="title">
            <span>当班设备时间开动率排行</span>
          </div>
          <q-table
            :data="rankTableData" :columns="rankColumns"
            row-key="id" class="scroll myTable-line rank-table"
            :loading="rankTableLoading" table-style="max-height: 468px"
            hide-bottom :pagination="{rowsPerPage: 0}"
            no-data-label="暂无数据">
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td key="rank" :props="props">
                  <span v-if="props.row.index > 3" class="text-center rank-index">{{ props.row.index }}</span>
                  <img v-else :src="'statics/img/'+props.row.index+'.png'" alt="">
                </q-td>
                <q-td key="device" :props="props">{{ props.row.deviceName }}</q-td>
                <q-td key="percent" :props="props">{{ props.row.operatingRate }}</q-td>
              </q-tr>
            </template>
          </q-table>
        </div>
        <div class="box">
          <div class="title">
            <span>消息列表</span>
            <!--            <q-btn class="float-right more-btn" flat dense color="primary" label="更多》" to="/main/message" />-->
          </div>
          <q-table
            :data="tableData" :columns="columns"
            row-key="id" class="scroll myTable-line"
            :loading="tableLoading" table-style="max-height: 468px"
            hide-bottom :pagination="{rowsPerPage: 0}"
            no-data-label="暂无数据">
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td key="type" :props="props">
                  <span class="round" :style="{'background-color':eventColor[props.row.type]}"></span>
                  {{ props.row.statusText }}
                </q-td>
                <q-td key="device" :props="props">{{ props.row.deviceName }}({{props.row.assetNumber}})</q-td>
                <q-td key="time" :props="props">{{ props.row.time }}</q-td>
              </q-tr>
            </template>
          </q-table>
        </div>
      </div>
      <sel-plant-dialog ref="selPlantDialog" :treeList="treeList" @submit="changeSel" />
      <pie-dialog ref="pieDialog" :chart-color="eventColor" :explain="eventExplain" />
      <cur-status-dialog ref="curStatusDialog" />
      <line-dialog ref="lineDialog" />
      <bar-dialog ref="barDialog" />
    </div>
<!--  </q-scroll-area>-->
</template>

<script>
import Box from './components/box'
import Pie from './components/pie'
import CurStatus from './components/cur-status'
import CurStatusDialog from './components/cur-status-dialog'
import SelPlantDialog from './components/sel-plant-dialog'
import PieDialog from './components/pie-dialog'
import LineDialog from './components/line-dialog'
import BarDialog from './components/bar-dialog'
import echarts from 'echarts'
import { mapGetters } from 'vuex'
import { getOrganizeNested } from 'src/boot/factory/organize'
// import { getRealtimeStatus, getCurStatus, getStopReason,
import { getRealtimeStatus, getStopReason, getCurStatus,
  getBadChart, getShifts, getDeviceRate, getMessage } from 'src/boot/home/home'
import refreshMixin from '../../assets/js/refresh-mixin'
import { date } from 'quasar'
import _ from 'lodash'
import { addListener } from 'resize-detector'
export default {
  name: 'stats-statistics',
  mixins: [refreshMixin],
  data () {
    return {
      showScale: false, // 是否可以缩放
      pageName: 'home', // 页面name
      treeList: [], // 分厂车间树形数据
      selTree: {
        factory: {},
        plant: {}
      },
      isFindPlant: false,
      shifts: {
        name: '',
        id: '',
        startTime: '',
        endTime: '',
        workFlag: 0
      },
      workFlagName: '',
      // 实时状态
      realTimeStatus: {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alert: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      },
      // 实时数量
      realTimeTotal: 0,
      // 缓存实时状态数据
      realTimeStatusData: [],
      // 当班状态
      curStatus: {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alarm: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      },
      // 当班数量
      curTotal: 0,
      barChart: null, // 当班停机原因柱状图
      barData: [],
      // 当班不良统计
      lineChart: null, // 当班不良统计柱状图
      lineData: [],
      // 事件列表
      tableLoading: false, // table加载时使用
      tableData: [], // table数据
      columns: [ // 事件标题
        { name: 'type', align: 'left', label: '状态类型', field: 'type', check: true },
        { name: 'device', align: 'left', label: '设备', field: 'device', check: true },
        { name: 'time', align: 'left', label: '发生时间', field: 'time', check: true, style: 'width: 158px' }
      ],
      // 开动率排行榜列表
      rankTableLoading: false, // table加载时使用
      rankTableData: [], // table数据
      rankColumns: [ // 事件标题
        { name: 'rank', align: 'left', label: '当前排名', field: 'rank', check: true },
        { name: 'device', align: 'left', label: '设备', field: 'device', check: true },
        { name: 'percent', align: 'left', label: '设备时间开动率', field: 'percent', check: true, style: 'width: 80px' }
      ],
      // 事件对应颜色
      eventColor: {
        process: '#18D77F', // 加工
        stop: '#FF8559', // 停机
        breaks: '#999999', // 断开
        offLine: '#666666', // 离线
        alert: '#E43434', // 报警
        changeLine: '#AC70F2', // 换线
        fault: '#F7B82D', // 故障
        repair: '#44D8C6' // 维修
      },
      // 事件名称列表
      eventExplain: {
        process: '加工',
        stop: '停机',
        breaks: '断开',
        offLine: '离线',
        alert: '报警',
        changeLine: '换线',
        fault: '故障',
        repair: '维修'
      },
      // 值对应事件名称
      eventValue: {
        0: 'stop',
        1: 'process',
        2: 'offLine',
        3: 'breaks',
        4: 'alert',
        5: 'changeLine',
        6: 'fault',
        7: 'repair',
        51: 'process'
      },
      timer: null,
      stopRequest: false,
      //  mqtt实例
      client: null,
      isProd: false // 是否是生产环境
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'permissions'])
  },
  watch: {
    permissions () {
      if (this.permissions.indexOf(74) > -1) {
        let self = this
        this.isProd = false
        this.getSelData()
        window.onresize = () => {
          return (() => {
            self.barChart.resize()
            self.lineChart.resize()
          })()
        }
      } else {
        this.isProd = true
      }
    }
  },
  created () {
    // 判断有没有机台状态模块
    if (this.permissions.indexOf(74) > -1) {
      this.isProd = false
      this.getSelData()
    } else {
      this.isProd = true
    }
  },
  mounted () {
    addListener(this.$refs.barChart, this.$utils.debounce(() => {
      if (this.barChart) {
        this.barChart.resize()
      }
      if (this.lineChart) {
        this.lineChart.resize()
      }
    }, 100))

    // this._listenAlt()
    // 判断有没有机台状态模块
    if (this.permissions.indexOf(74) > -1) {
      let self = this
      window.onresize = () => {
        return (() => {
          self.barChart.resize()
          self.lineChart.resize()
        })()
      }
    }
  },
  destroyed () {
    clearTimeout(this.timer)
    this.timer = null
  },
  methods: {
    // 图表缩放
    changeScale () {
      let optionBarChart = _.cloneDeep(this.barChart.getOption())
      optionBarChart.dataZoom[0].disabled = !this.showScale
      this.barChart.clear()
      this.barChart.setOption(optionBarChart)
      let optionLineChart = _.cloneDeep(this.lineChart.getOption())
      optionLineChart.dataZoom[0].disabled = !this.showScale
      this.lineChart.clear()
      this.lineChart.setOption(optionLineChart)
    },
    // 刷新
    refreshInfo () {
      if (process.env.COMPILE_ENV !== 'prod') {
        clearTimeout(this.timer)
        this.timer = null
        this.getSelData()
      }
    },
    // 初始化mqtt
    initMqtt () {
      // 生成一个唯一的userId用于连接盒子，此id必须唯一
      const userId = 'webClient' + this.userInfo.user_id.toString() + Date.parse(new Date()).toString()
      // 创建mq实例
      this.client = new window.Paho.MQTT.Client(
        this.CommonConfig.mqttConfig.MQTT_SERVICE,
        Number(this.CommonConfig.mqttConfig.MQRR_PORT),
        userId)
      // 连接服务器并注册连接成功处理事件
      this.client.connect({ onSuccess: this.onConnect })
      // 注册连接断开处理事件
      this.client.onConnectionLost = this.onConnectionLost
      // 注册消息接收处理事件
      this.client.onMessageArrived = this.onMessageArrived
    },

    // 连接成功，订阅并发送消息
    onConnect () {
      console.log('连接成功')
      // console.log(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.realTimeStatus.subscribeTopic}${this.selTree.plant.id}`)
      // 订阅主题（机床状态）
      // this.client.subscribe(
      //   `${this.CommonConfig.mqttConfig.MQTT_TOPIC.realTimeStatus.subscribeTopic}#`,
      //   { qos: 1 }
      // )
      this.onSubscribe()
    },
    // 订阅消息
    onSubscribe () {
      this.client.subscribe(
        `${this.CommonConfig.mqttConfig.MQTT_TOPIC.realTimeStatus.subscribeTopic}${this.selTree.plant.id}`,
        { qos: 1 }
      )
    },
    /**
     * 接受盒子返回消息
     * @param {string} message
     */
    onMessageArrived (message) {
      let data = JSON.parse(message.payloadString)
      // console.log(data)
      // 状态码优先级定义
      let priority = {
        '1': [0, 1, 2, 3],
        '2': [4],
        '3': [5],
        '4': [6, 7]
      }
      // 实时状态分布
      if (this.realTimeStatusData[data.boxId]) {
        let statusArr = JSON.parse(JSON.stringify(this.realTimeStatusData[data.boxId]))
        // console.log(this.realTimeStatusData[data.boxId])
        switch (data.status) {
          // 判断是否是报警相关
          case 4:
            // 报警时，数据变成[6,5,4,1],[5,4,1],[4,1],[5,4,2],[4,2],[5,4,3],[4,3]
            if (data.statusText === '报警') {
              // 长度为1时，把4塞进去就好了，变成[4,1]
              if (statusArr.length === 1) {
                statusArr.unshift(data.status)
              } else {
                // 长度不为1
                // 如果不存在4(数据是[6,5,1],[5,1],[6,1])，就在倒数第二位插入4（数据变成[6,5,4,1][5,4,1],[6,4,1]）
                // 如果存在4，就保持原状
                if (statusArr.indexOf(4) === -1) {
                  // 在倒数第二位插入4
                  statusArr.splice(-1, 0, data.status)
                }
              }
            } else if (data.statusText === '报警解除') {
              // 报警解除时，去掉4
              statusArr = statusArr.filter(item => {
                return item !== 4
              })
            }
            break
          // 换线
          case 5:
            // 换线时，数据变成[6,5,4,1],[5,4,1], [5,1], [5,4,2], [5,2], [5,4,3], [5,3]
            if (statusArr.length === 1) {
              // 长度为1时，把5塞进去就好了，变成[5,1]
              statusArr.unshift(data.status)
            } else {
              // 长度不为1时
              // 如果不存在5（数据是[4,1],[6,1]），就把5插入进去（数据变成[5,4,1],[6,5,1]）
              // 如果存在5（数据是[5,1]）,就保持原状
              if (statusArr.indexOf(5) === -1) {
                // 判断数组里存在高级别的6,7,就在第二位添加5
                if (statusArr.indexOf(priority['4'][0]) > -1 || statusArr.indexOf(priority['4'][1]) > -1) {
                  statusArr.splice(1, 0, data.status)
                } else {
                  // 否则在第一位插入5
                  statusArr.splice(0, 0, data.status)
                }
              }
            }
            break
          // 换线结束，去掉5
          case 51:
            if (data.status === 51) {
              statusArr = statusArr.filter(item => {
                return item !== 5
              })
            }
            break
          // 故障、维修
          case 6:
          case 7:
            if (data.overFlag) {
              // 状态解除，去掉对应的错误码
              statusArr = statusArr.filter(item => {
                return item !== data.status
              })
            } else {
              // 状态添加
              // 故障时，数据变成[6,5,4,1],[6,4,1],[6,1]
              // 维修时，数据变成[7,5,4,1],[7,4,1],[7,1]
              if (statusArr.length === 1) {
                // 长度为1时，把状态塞进去就好了，变成[6,1]或者[7,1]
                statusArr.unshift(data.status)
              } else {
                // 长度不为1
                // 判断第一位是否是6或者7
                if (priority['4'].indexOf(statusArr[0]) > -1) {
                  // 第一位是最高级别，就替换
                  statusArr.splice(0, 1, data.status)
                } else {
                  // 第一位不是最高级别数据，就插入到第一位
                  statusArr.splice(0, 0, data.status)
                }
              }
            }
            break
          // 其他状态修改最后一位
          default:
            statusArr.splice(statusArr.length - 1, 1, data.status)
            break
        }
        this.realTimeStatusData[data.boxId] = statusArr
        // console.log(this.realTimeStatusData[data.boxId])
        this.realTimeStatus = this.initRealTimeStatus(this.realTimeStatusData)

        // 消息列表
        if (data.status === 4 || data.status === 6 || data.status === 7) {
          let hasMessageIndex = this.tableData.findIndex(item => {
            return date.formatDate(item.time, 'YYYY-MM-DD HH:mm:ss') === date.formatDate(data.time, 'YYYY-MM-DD HH:mm:ss') &&
              item.deviceID === data.deviceID && item.type === this.eventValue[Number(data.status)]
          })
          if (hasMessageIndex === -1) {
            let message = {
              ...data,
              type: this.eventValue[Number(data.status)],
              time: date.formatDate(data.time, 'YYYY-MM-DD HH:mm:ss')
            }
            if (data.status === 4) {
              message.eventDesc = data.alarmContent
            }
            this.tableData.unshift(message)
            // 只保留前20条
            this.tableData = this.tableData.length > 20 ? this.tableData.slice(0, 21) : this.tableData
          }
        }
      }
    },
    /**
     * 连接丢失
     * @param {{}} responseObject
     */
    onConnectionLost (responseObject) {
      console.log('连接断开事件')
      if (responseObject.errorCode !== 0) {
        // this.onConnect()
        console.log('onConnectionLost:' + responseObject.errorMessage)
        console.log('连接已断开')
      }
      this.client.connect({
        keepAliveInterval: 30,
        onSuccess: this.onConnect
      })
    },
    getSelData () {
      getOrganizeNested().then(res => {
        this.treeList = res.data
        console.log(this.treeList)
        if (res.data.length > 0) {
          this.setSelTree()
          this.initMqtt()
          this.getShifts()
        }
      })
    },
    getShifts () {
      if (this.timer === null) {
        clearTimeout(this.timer)
        this.timer = null
      }
      getShifts(this.selTree.plant.id).then(res => {
        if (res.data) {
          this.shifts.name = res.data.name || ''
          this.shifts.id = res.data.id || ''
          this.workFlag = res.data.workFlag || 0
          let workFlagName
          switch (this.workFlag) {
            case 0:
              workFlagName = '休息中'
              break
            case 1:
              workFlagName = '工作中'
              break
            case 2:
              workFlagName = '换班中'
              break
            case 3:
              workFlagName = '休息日'
              break
            default:
              workFlagName = '--'
              break
          }
          this.workFlagName = workFlagName
          this.shifts.startTime = res.data.startTime ? this.getTime(res.data.startTime) : ''
          this.shifts.endTime = res.data.endTime ? this.getTime(res.data.endTime) : ''
          this.$q.loading.show()
          if (String(this.shifts.id).length > 0) {
            this.getData()
            this.getRealData()
            this.refreshData()
          } else {
            // this.errMessage('当前时间没有启用的班制')
            this.removeData()
            clearTimeout(this.timer)
            this.timer = null
          }
        } else {
          // this.errMessage('当前时间没有启用的班制')
          this.removeData()
          clearTimeout(this.timer)
          this.timer = null
        }
      }).catch(() => {
        this.removeData()
        clearTimeout(this.timer)
        this.timer = null
      })
    },
    // 失败提示
    errMessage (message) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title">
<i class="iconfont icontubiao-52" ></i> 提示</p>`,
        message: message,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        }
      })
    },
    getTime (time) {
      let timeArr = time.split(':')
      return timeArr[0] + ':' + timeArr[1]
    },
    // 获取实时数据
    getRealData () {
      let params2 = this.getDateTime(this.shifts.startTime, this.shifts.endTime)
      getRealtimeStatus(params2, this.selTree.plant.id).then(res => {
        this.realTimeStatusData = res.data
        this.realTimeStatus = this.initRealTimeStatus(res.data)
        this.realTimeTotal = res.data.length
      })
      let params3 = {
        ...params2,
        workshopId: this.selTree.plant.id,
        pageSize: 20
      }
      getMessage(params3).then(res => {
        this.tableData = this.initAlertTableData(res.data)
      })
    },
    // 获取不是实时的数据
    getData () {
      // this.$q.loading.show()
      let params2 = this.getDateTime(this.shifts.startTime, this.shifts.endTime)
      let params1 = {
        ...params2,
        workshopId: this.selTree.plant.id
      }
      getCurStatus(params1).then(res => {
        console.log('12222222222')
        // this.curTotal = this.getTotal(res.data)
        this.curTotal = res.data.total
        this.curStatus = res.data
        delete this.curStatus.total
      })
      // 获取停机原因
      getStopReason(params2, this.selTree.plant.id).then(res => {
        this.barData = this.initStopReason(res.data)
        this.setBarOption()
      })
      // 获取当班不良统计
      getBadChart(params2, this.selTree.plant.id, this.shifts.id).then(res => {
        this.lineData = res.data
        this.setLineOption()
      })
      let params3 = {
        ...params2,
        shiftId: this.shifts.id
      }
      // 获取设备开动率
      getDeviceRate(params3, this.selTree.plant.id, this.shifts.id).then(res => {
        this.rankTableData = this.initRankTableData(res.data)
      })
      console.log(this.workFlagName)
      this.$q.loading.hide()
    },
    // 重构实时状态分布
    initRealTimeStatus (info) {
      let realTimeStatus = {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alert: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      }
      for (let key in info) {
        switch (info[key][0]) {
          case 0:
            ++realTimeStatus.stop
            break
          case 1:
          case 51:
            ++realTimeStatus.process
            break
          case 2:
            ++realTimeStatus.offLine
            break
          case 3:
            ++realTimeStatus.breaks
            break
          case 4:
            ++realTimeStatus.alert
            break
          case 5:
            ++realTimeStatus.changeLine
            break
          case 6:
            ++realTimeStatus.fault
            break
          case 7:
            ++realTimeStatus.repair
            break
        }
      }
      return realTimeStatus
    },
    // 重构设备开动率数据
    initRankTableData (data) {
      return data.map((item, index) => {
        return {
          ...item,
          index: index + 1,
          operatingRate: (item.operatingRate * 100).toFixed(2) + '%'
        }
      })
    },
    // 重构消息数据
    initAlertTableData (data) {
      return data.map(item => {
        return {
          ...item,
          type: this.eventValue[Number(item.statusCode)],
          time: date.formatDate(item.time, 'YYYY-MM-DD HH:mm:ss')
        }
      })
    },
    // 重构停机原因
    initStopReason (data) {
      return data.map(item => {
        return {
          ...item,
          value: (item.value / 60).toFixed(2)
        }
      })
    },
    // 刷新数据
    refreshData () {
      if (this.$route.name !== 'home') {
        clearTimeout(this.timer)
        this.timer = null
        return
      }

      this.timer = setTimeout(this.getShifts, 300000)

      // let { end } = this.getDateTime(this.shifts.startTime, this.shifts.endTime)
      // let cur = new Date()
      // let endDate = new Date(end)
      // if (cur.getTime() > endDate.getTime()) {
      //   clearTimeout(this.timer)
      //   this.timer = null
      //   this.getShifts()
      // } else {
      //   if (String(this.shifts.id).length > 0) {
      //     this.getData()
      //     this.timer = setTimeout(this.refreshData, 60000)
      //   }
      // }
      // setTimeout(() => {}, 60000)
      // this.timer = setInterval(() => {
      //   console.log(this.$route.name)
      //   if (this.$route.name === 'home') {
      //     let { end } = this.getDateTime(this.shifts.startTime, this.shifts.endTime)
      //     let cur = new Date()
      //     let endDate = new Date(end)
      //     if (cur.getTime() > endDate.getTime()) {
      //       clearInterval(this.timer)
      //       this.timer = null
      //       this.getShifts()
      //     } else {
      //       if (String(this.shifts.id).length > 0) {
      //         this.getData()
      //       }
      //     }
      //   } else {
      //     clearTimeout(this.timer)
      //     this.timer = null
      //   }
      // }, 60000)
    },
    // 让数据为空
    removeData () {
      // 班制
      this.shifts = {
        name: '',
        id: '',
        startTime: '',
        endTime: '',
        workFlag: 0
      }
      // 实时状态
      this.realTimeStatus = {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alert: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      }
      // 实时数量
      this.realTimeTotal = 0
      // 当班状态
      this.curStatus = {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alarm: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      }
      // 当班数量
      this.curTotal = 0
      this.barData = []
      this.lineData = []
      // this.barData.forEach(item => {
      //   item.value = 0
      // })
      // this.lineData.forEach(item => {
      //   item.value = 0
      // })
      // 报警列表
      this.tableData = []
      this.rankTableData = []
      // 设备开动率
      this.rankTableData = []
      this.setBarOption()
      this.setLineOption()
      this.$q.loading.hide()
    },
    // 获取一共的数量
    getTotal (info) {
      let total = 0
      for (let key in info) {
        total += info[key]
      }
      return total
    },
    setSelTree () {
      for (let i = 0; i < this.treeList.length; i++) {
        if (this.treeList[i].childrenCount > 0) {
          this.selTree.factory = this.treeList[i]
          for (let j = 0; j < this.treeList[i].children.length; j++) {
            if (this.treeList[i].children[j].label !== 'default') {
              this.selTree.plant = this.treeList[i].children[j]
              this.isFindPlant = true
              break
            }
          }
          if (this.isFindPlant) {
            break
          }
        }
      }
      if (!this.isFindPlant) {
        this.$q.dialog({
          title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-53" ></i> 请先在“基础数据-工厂建模”里创建的分厂下面创建车间！</p>`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        })
      }
    },
    // 选择车间
    changeSel (selTree) {
      if (selTree.factory.hash !== this.selTree.factory.hash || selTree.plant.hash !== this.selTree.plant.hash) {
        this.selTree = JSON.parse(JSON.stringify(selTree))
        this.getShifts()
        this.onSubscribe()
      }
    },
    // 显示柱状图
    setBarOption () {
      const xData = this.barData.map(item => {
        if (item.name.length > (11 - this.lineData.length)) {
          let newName = item.name.slice(0, 12 - this.lineData.length)
          newName += '...'
          return newName
        }
        return item.name
      })
      let max = this.getMax(this.barData)
      let option = {
        grid: {
          top: 35,
          bottom: 30,
          left: String(max).length < 4 ? 40 : 60,
          right: 0
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true
            }
          },
          formatter: (params, ticket, callback) => {
            let htmlStr = ''
            let value = params[0].value
            let color = `linear-gradient(#44D8C6, #5F77FD)`
            htmlStr += '<div>'
            htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-image:' + color + ';"></span>'
            htmlStr += '<span>' + params[0].name + '：</span>'
            htmlStr += value + '分钟'

            htmlStr += '</div>'
            return htmlStr
          }
        },
        dataZoom: [
          {
            type: 'inside',
            disabled: !this.showScale,
            xAxisIndex: 0
          }
        ],
        xAxis: {
          type: 'category',
          data: xData,
          axisTick: {
            show: false // 隐藏X轴刻度
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333333', // X轴文字颜色
              fontSize: 14
            },
            interval: 0
          },
          axisLine: {
            show: true, // 隐藏X轴轴线
            lineStyle: {
              color: '#d3d3d3'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '时间(min)',
          nameTextStyle: {
            color: '#333333',
            fontSize: 14
          },
          nameGap: 20,
          // interval: 30,
          splitLine: {
            show: true
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333333',
              fontSize: 14
            }
          },
          axisLine: {
            show: false
          }
        },
        series: {
          type: 'bar',
          barWidth: 16,
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: '#44D8C6'
              },
              {
                offset: 1,
                color: '#5F77FD'
              }]),
              barBorderRadius: [6, 6, 0, 0]
            }
          },
          label: {
            show: true,
            position: 'top',
            color: '#5F77FD',
            fontSize: 12
          },
          data: this.barData
        }
      }
      if (this.barChart === null) {
        this.barChart = echarts.init(this.$refs.barChart)
      }
      this.barChart.setOption(option)
    },
    // 显示折线图
    setLineOption () {
      const xData = this.lineData.map(item => {
        if (item.name.length > (11 - this.lineData.length)) {
          let newName = item.name.slice(0, 12 - this.lineData.length)
          newName += '...'
          return newName
        }
        return item.name
      })
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              type: 'dashed'
            }
          },
          formatter: function (params, ticket, callback) {
            let htmlStr = ''
            let value = params[0].value
            let color = params[0].color
            htmlStr += '<div>'
            htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>'

            htmlStr += '<span>' + params[0].name + '：</span>'
            htmlStr += value + '个'

            htmlStr += '</div>'
            return htmlStr
          }
        },
        dataZoom: [
          {
            type: 'inside',
            disabled: !this.showScale,
            xAxisIndex: 0
          }
        ],
        grid: {
          top: 35,
          bottom: 30,
          left: 40,
          right: 0
        },
        xAxis: [{
          type: 'category',
          data: xData,
          axisTick: {
            show: false // 隐藏X轴刻度
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333333', // X轴文字颜色
              fontSize: 14
            },
            interval: 0
          },
          axisLine: {
            show: true, // 隐藏X轴轴线
            lineStyle: {
              color: '#d3d3d3'
            }
          }
        }],
        yAxis: [{
          type: 'value',
          name: '数量',
          nameTextStyle: {
            color: '#333333',
            fontSize: 14
          },
          nameGap: 20,
          // interval: 30,
          splitLine: {
            show: true
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333333',
              fontSize: 14
            }
          },
          axisLine: {
            show: false
          }
        }],
        series: [{
          name: '开动率',
          type: 'line',
          data: this.lineData,
          lineStyle: {
            normal: {
              width: 5,
              color: '#5F77FD',
              shadowColor: 'rgba(95, 119, 253, 0.3)',
              shadowBlur: 10,
              shadowOffsetY: 20
            }
          },
          symbolSize: 15,
          itemStyle: {
            normal: {
              color: '#5F77FD',
              borderWidth: 3,
              borderColor: '#5F77FD'
            },
            emphasis: {
              color: '#5F77FD',
              borderColor: '#5F77FD'
            }
          },
          smooth: true
        }]
      }
      if (this.lineChart === null) {
        this.lineChart = echarts.init(this.$refs.lineChart)
      }
      this.lineChart.setOption(option)
    },
    // 显示选择车间的弹框
    showSelPlantDialog () {
      if (!this.isFindPlant) {
        this.$q.dialog({
          title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-53" ></i> 请先在“基础数据-工厂建模”里创建的分厂下面创建车间！</p>`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        })
        return
      }
      this.$refs.selPlantDialog.showDialog(this.selTree)
    },
    // 放大Pie
    showPieDialog (info, total, title, type) {
      if (type === 'time') {
        this.$refs.curStatusDialog.showDialog(info, total, title)
      } else {
        this.$refs.pieDialog.showDialog(info, total, title, type)
      }
    },
    // 放大折线图
    showLineDialog () {
      this.$refs.lineDialog.showDialog(this.lineData)
    },
    // 放大柱状图
    showBarDialog () {
      this.$refs.barDialog.showDialog(this.barData)
    },
    // 根据时分获取日期时间
    getDateTime (start, end) {
      let startArr = start.split(':')
      let startH = Number(startArr[0])
      let startM = Number(startArr[1])
      let newDateStart = date.buildDate({ hours: startH, minutes: startM, seconds: 0 })

      let endArr = end.split(':')
      let endH = Number(endArr[0])
      let endM = Number(endArr[1])
      let newDateEnd = date.buildDate({ hours: endH, minutes: endM, seconds: 0 })

      let newDate = date.buildDate({ seconds: 0 })
      if (newDate.getTime() > newDateStart.getTime() && newDate.getTime() > newDateEnd.getTime()) {
        newDateEnd = date.addToDate(newDateEnd, { days: 1 })
      } else if (newDate.getTime() < newDateStart.getTime() && newDate.getTime() < newDateEnd.getTime()) {
        newDateStart = date.subtractFromDate(newDateStart, { days: 1 })
      }

      let startResult = date.formatDate(newDateStart, 'YYYY-MM-DDTHH:mm:ss')
      let endResult = date.formatDate(newDateEnd, 'YYYY-MM-DDTHH:mm:ss')

      return { start: startResult, end: endResult }
    },
    // 获取最大值
    getMax (arr) {
      if (arr.length === 0) {
        return 0
      }
      let valArr = arr.map(item => item.value)
      return Math.max.apply(null, valArr)
    }
  },
  components: {
    Box,
    Pie,
    CurStatus,
    CurStatusDialog,
    SelPlantDialog,
    PieDialog,
    LineDialog,
    BarDialog
  }
}
</script>

<style scoped lang="stylus">
 //>>> .q-toggle__inner {
 //  width: 56px;
 //  min-width: 56px;
 //  height: 40px;
 //  padding: 10px 12px;
 //  height: 35px;
 //}
 //>>>.q-toggle__thumb-container {
 //  left: 10px;
 //  right: auto;
 //  top: 7px;
 //  transform: translate3d(0, 0, 0);
 //  transition: transform 0.22s cubic-bezier(0.4, 0, 0.2, 1);
 //}

.fuck {
  .row {
    justify-content space-between
  }

  .top {
    margin-bottom 0
  }

  .bottom {
    padding-bottom 20px !important
  }

  .left.top {
    .pic {
      background-image url("../../statics/img/pic-1.png")
      background-repeat no-repeat
      background-size 100% 100%
      height 280px
    }
  }

  .left.bottom {
    padding 6px
    border-radius 6px

    .pic {
      border-radius 6px
      background-image url("../../statics/img/pic-3.png")
      background-repeat no-repeat
      background-size 100% 100%
      width 100%
      height 1300px
    }
  }

  .right {
    width 32%

    &.top {
      .pic {
        background-image url("../../statics/img/pic-2.png")
        background-repeat no-repeat
        background-size 100% 100%
        height 280px
      }
    }

    &.bottom {
      padding 6px
      border-radius 6px

      .pic {
        background-image url("../../statics/img/pic-4.png")
        background-repeat no-repeat
        background-size 100% 100%
        height 567px
      }
    }
  }
}
.prod{
  background url("../../statics/img/home-bg.png") no-repeat center
  background-size cover
  position relative
  border-radius 6px
  overflow hidden
  img{
    height 95%
    max-width 95%
    position absolute
    bottom 0
    left 50%
    transform translateX(-50%)
  }
  .txt{
    font-size 40px
    color #fff
    font-weight bold
    position absolute
    bottom 50%
    left 50%
    transform translate(-50%, 30%)
    background-color rgba(0,0,0,.5)
    border-radius 20px
    padding 48px 40px
    line-height 1
    white-space nowrap
  }
}
.home-scroll{
  height calc(100%+7px) !important
  margin-top -7px
  margin-right -24px
  padding-right 24px
  overflow-y overlay
}
.home{
  display flex
  flex-wrap nowrap
  justify-content space-between
  .left{
    width 66.67%;
    padding-right 12px
    .top-head{
      margin-bottom 17px
      /*padding 0 22px*/
      font-size 18px
      line-height 18px
      font-weight bold
      color #333
    }
    .small-title{
      font-size 14px
      font-weight normal
    }
    .flex-item{
      flex 1
      margin-right 24px
      &:last-child{
        margin-right 0
      }
      .content{
        height 304px
        .progress-list{
          height calc(100% - 36px)
          display flex
          flex-direction column
          justify-content space-around
          li{
            display flex
            font-size 14px
            .progress{
              flex 1 auto
              margin 0 20px
            }
          }
        }
      }
    }
    .line2, .line3{
      margin-top 24px
      height 380px
      padding 0
      .barChart, .lineChart{
        width 100%
        height 304px
      }
    }
  }
  .right{
    /*padding-top 34px*/
    padding-left 12px
    width 33.33%
    .top-head{
      /*padding-right 16px*/
      /*margin-bottom 13px*/
      .more-btn{
        margin-top -5px
      }
    }
    .box{
      height 544px
      padding 20px
      background-color #fff
      border-radius 6px
      line-height 1
      &:last-child{
        margin-top 24px
      }
      .title{
        margin-bottom 20px
        font-size 16px
        line-height 1
        .float-right{
          position relative
          top -5px
          right -5px
        }
        .more-btn{
          margin-top -4px
        }
      }
      .myTable-line{
        margin 0
      }
      .round{
        display inline-block
        vertical-align middle
        width 14px
        height 14px
        line-height 14px
        border-radius 7px
        margin-right 10px
      }
    }
    .rank-index{
      display inline-block
      min-width 27px
    }
    .myTable-line{
      position relative
      z-index 10
    }
  }
}
</style>
<style lang="stylus">
.home{
  .right .rank-table{
    tbody tr{
      &:first-child, &:nth-child(2), &:nth-child(3){
        background-color #fff
        &:hover{
          background-color #cfd6fe
        }
      }
      &:first-child td, &:nth-child(2) td, &:nth-child(3) td{
        position sticky
        z-index 1
      }
      &:first-child td{
        top 48px
      }
      &:nth-child(2) td{
        top 96px
      }
      &:nth-child(3) td{
        top 144px
      }
    }
  }
}
</style>
